<template>
  <div class="flex align-center">
    <el-button type="primary" :disabled="taskIdList.length !== 0" @click="otdrClick">{{
      $t('BIZ_FUNC_OTDR_TEST')
    }}</el-button>
    <div class="test-progress flex">
      <template v-if="completed">
        {{ $t('TEST_COMPLETED') }}
      </template>
      <template v-if="taskIdList.length !== 0">
        <process-bar :cur-process="progress">
          <span slot="doing" class="font-mini">{{ $t('OTDR_TEST_STATUS_TEST') }}</span>
          <span slot="done" class="font-mini">{{ $t('TEST_COMPLETED') }}</span>
        </process-bar>
      </template>
      <span v-if="failed" class="text-danger" :class="isTopo ? 'w-150' : ''">
        {{ $t('TEST_FAILED') }}，{{ $utils.handleServiceI18n(failMsg) }}
      </span>
    </div>
    <!-- 选择测试方向 -->
    <el-dialog
      :visible.sync="showConfirm"
      width="420px"
      :before-close="closeConfirm"
      append-to-body
    >
      <div>
        <p>{{ $t('TEST_OTDR') }}</p>
        <div class="mb-20 mt-20 flex align-center">
          <span>{{ $t('TESTING_DIRECTION') }}：</span>
          <el-select v-model="direction" style="width: 100px" size="mini">
            <!-- <el-option :label="$t('BOTHWAY')" value="DOUBLE" /> -->
            <el-option :label="$t('A_END')" value="A" />
            <el-option :label="$t('Z_END')" value="Z" />
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showConfirm = false">{{ $t('CANCEL') }}</el-button>
        <el-button type="primary" @click="$debounce(otdrTest)">{{ $t('CONFIRM') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import TaskGroupApi from '@/api/oen/TaskGroup'
  import segmentChannelApi from '@/api/oen/SegmentChannelApi'
  import faultLocationApi from '@/api/oen/FaultLocationApi'
  import logicSegmentApi from '@/api/oen/LogicSegmentApi'
  import { checkAfs, correctChannel } from '@/utils/common'
  import taskGroup from '@/api/oen/TaskGroup'
  import ProcessBar from './ProcessBar'

  export default {
    components: { ProcessBar },
    props: {
      formData: {
        required: true,
        type: Object,
        default: () => {}
      },
      isTopo: {
        type: Boolean,
        default: false
      }
    },
    inject: ['parentVM'],
    data() {
      return {
        progress: 0,
        completed: false,
        taskIdList: [],
        showConfirm: false,
        direction: 'A',
        failed: false,
        failMsg: '',
        contrastMsg: [],
        queryCount: 0,
        progressTimer: null,
        processId: ''
      }
    },
    computed: {
      ...mapGetters(['taskProcess'])
    },
    watch: {
      taskProcess(newVal) {
        if (this.taskIdList.length === 0) return
        this.taskIdList.forEach(i => {
          if (i.taskId === newVal.taskId) {
            i.progress = Math.max(newVal.progress, i.progress)
            if (newVal.error || newVal.errorInfo) {
              this.$message.closeAll()
              this.$message.error(this.$utils.handleServiceI18n(newVal.errorInfo.desc || ''))
              this.testFail(newVal.errorInfo.desc || '')
              return
            }
          }
        })
        const progress =
          this.taskIdList.reduce((total, curr) => {
            return total + curr.progress
          }, 0) / this.taskIdList.length
        if (progress >= 100) {
          this.completed = true
          this.refreshLoss()
        }
        this.progress = parseInt(progress)
      },
      progress(newVal) {
        this.progressTimer && clearTimeout(this.progressTimer)
        this.progressTimer = null
        if (newVal < 100) {
          this.getByProcessId()
        }
      }
    },
    methods: {
      getByProcessId() {
        const _this = this
        this.progressTimer = setTimeout(() => {
          TaskGroupApi.getByProcessId({ processId: _this.processId }).then(res => {
            if (res.status === 'SUCCESS') {
              _this.completed = true
              _this.refreshLoss()
            } else if (res.status === 'READY' || res.status === 'PROCESS') {
              _this.progress = parseInt(res.progress)
            } else {
              _this.testFail(_this.$t('TEST_FAILED'))
            }
            _this.progressTimer = null
          }).catch(e => {
            _this.getByProcessId()
          })
        }, 3 * 60 * 1000)
      },
      // 测试按钮点击
      async otdrClick() {
        this.direction = 'A'
        // 判断选中的通道AFS设备是否可用
        const checkeAfs = await checkAfs(this.formData, 'OTDR_TEST', true)
        if (!checkeAfs) return
        this.showConfirm = true

        //   const narmalStatus = [
        //   'IDLE',
        //   'LOWER_POWER',
        //   'LOW_POWER',
        //   'READY',
        //   'CANCEL',
        //   'STANDBY'
        // ]

        // const afsList = this.formData.routeData.segmentList
        //   .filter(i => i.endNodeCategory === 'AFS' && !narmalStatus.includes(i.endNode.afsStatus))
        //   .map(i => i.endNode.nodeName)
        // if (afsList.length === 0) {
        //   this.showConfirm = true
        // } else {
        //   this.$confirm(
        //     this.$t('CONTINUE_TEST', {
        //       msg: afsList.join()
        //     }),
        //     {
        //       confirmButtonText: this.$t('CONTINUE'),
        //       cancelButtonText: this.$t('CANCEL'),
        //       type: 'warning'
        //     }
        //   )
        //     .then(() => {
        //       this.showConfirm = true
        //     })
        //     .catch(() => {})
        // }
        // console.log(this.formData)
      },
      testFail(msg) {
        this.completed = false
        this.taskIdList = []
        this.failed = true
        this.failMsg = msg
        this.refreshLoss()
      },
      // 刷新链损值
      refreshLoss() {
        this.taskIdList = []
        this.contrastMsg = []
        this.queryCount = 0
        this.$emit('taskChange', false)
        const channelList = this.formData.routeData.channelList
        // console.log('channelList', channelList)
        channelList.forEach((i, index) => {
          i.checked && this.getResult(i, index)
        })
      },
      // 获取otdr测试结果(用index强制刷新formData)
      getResult(channelData, index) {
        const ids = channelData.segmentList.map(i => i.channelId)
        segmentChannelApi.getByChannelIdList({ ids: ids }).then(res => {
          this.queryCount++
          channelData.segmentList.forEach((i, segmetIndex) => {
            const resData = res.find(j => j.channelId === i.channelId)
            if (resData.status === i.status) {
              const realData = correctChannel(resData, resData.startNodeId !== i.startNodeId)
              channelData.segmentList[segmetIndex] = { ...i, ...realData }
            } else {
              const msg = this.$t('CHANNEL_STATUS_CHANGED', {
                msg1: this.formData.routeData.segmentList[segmetIndex].segmentName,
                msg2: index + 1
              })
              this.contrastMsg.push(msg)
            }
          })
          const loss = res.reduce((prev, cur) => {
            return prev + (cur.linkLoss || 0)
          }, 0)
          this.$set(this.formData.routeData.channelList, index, { ...channelData, loss: loss })
          this.formData.channelData = this.formData.routeData.channelList.filter(i => i.checked)
          this.$emit('taskChange', false)
          if (this.queryCount === this.formData.channelData.length && this.contrastMsg.length > 0) {
            this.$message({
              message: this.contrastMsg.join(' <br/> '),
              type: 'error',
              dangerouslyUseHTMLString: true,
              showClose: true,
              duration: 60 * 1000
            })
          }
        })
      },

      closeConfirm() {
        this.showConfirm = false
      },
      // otdr测试
      async otdrTest() {
        let portList = []
        this.formData.channelData.forEach(i => {
          const linkData = i.segmentList.map((j, index) => {
            return {
              networkSegment: this.formData.routeData.segmentList[index],
              segmentChannel: j
            }
          })
          const channelPortList = []
          let physicStruct = []
          i.segmentList.forEach((j, jIndex) => {
            const lastAfs = channelPortList.length
              ? channelPortList[channelPortList.length - 1]
              : null
            physicStruct.push(j.segmentId)
            if (j.startPortCategory === 'VARIABLE_POINT' && this.direction === 'Z') {
              const item = {
                deviceId: j.startNodeId,
                portId: j.startPortId,
                deviceData: this.formData.routeData.segmentList[jIndex].startNode,
                portData: j.startPort,
                testDirection: 'Z',
                physicStruct: physicStruct,
                networkLinkChannelBoList: linkData
              }
              if (lastAfs && lastAfs.deviceId === item.deviceId) {
                channelPortList.pop()
              }
              channelPortList.push(item)
            }
            if (j.endPortCategory === 'VARIABLE_POINT' && this.direction === 'A') {
              const item = {
                deviceId: j.endNodeId,
                deviceData: this.formData.routeData.segmentList[jIndex].endNode,
                portData: j.endPort,
                portId: j.endPortId,
                testDirection: 'A',
                physicStruct: physicStruct,
                networkLinkChannelBoList: linkData
              }
              if (!lastAfs || lastAfs.deviceId !== item.deviceId) {
                channelPortList.push(item)
              }
            }
            if (j.endPortCategory === 'VARIABLE_POINT') {
              physicStruct = []
            }
          })
          if (channelPortList.length > 0) {
            this.direction === 'A' && channelPortList.shift()
            this.direction === 'Z' && channelPortList.pop()
          }
          portList = [...portList, ...channelPortList]
        })
        // console.log('this.portList', portList)
        const structQueryData = {}
        const portIdList = []
        portList.forEach(i => {
          structQueryData[i.portId] = i.physicStruct
          portIdList.push(i.portId)
        })
        const linkSegmentList = await logicSegmentApi.getByStructMap(structQueryData)
        // 获取每个端口的测试参数
        const otdrParam = await faultLocationApi.otdrParam({
          portIdList: portIdList.join()
        })
        const noParamPort = {}
        portList.forEach(i => {
          i.linkSegmentId = linkSegmentList[i.portId]
          delete i.physicStruct
          if (otdrParam[i.portId]) {
            i.otdrParam = otdrParam[i.portId]
            delete i.deviceData
            delete i.portData
          } else {
            if (noParamPort[i.deviceId]) {
              noParamPort[i.deviceId].portList.push(i.portData.bizName)
            } else {
              noParamPort[i.deviceId] = {
                deviceName: i.deviceData.nodeName,
                portList: [i.portData.bizName]
              }
            }
          }
        })
        // 有端口未设置参考曲线不能继续
        if (Object.keys(noParamPort).length) {
          const msg = Object.keys(noParamPort).map(i => {
            return this.$t('PORT_OF_DEVICE', {
              msg1: noParamPort[i].deviceName,
              msg2: noParamPort[i].portList.join()
            })
          })
          this.$message.error(msg.join() + '，' + this.$t('NO_CURVE_NO_TEST'))
          return
        }
        // console.log('portList', portList)
        this.submitData(portList)
      },
      // 提交otdr测试
      submitData(portList) {
        console.log(this.formData)
        const processName = this.formData.bizName || this.$t('INTELLIGENT_CONNECT')
        const startNodeId =
          this.formData.startNodeId || this.formData.aNodeId || this.formData.aPortData.nodeId
        const endNodeId =
          this.formData.endNodeId || this.formData.zNodeId || this.formData.zPortData.nodeId
        const params = {
          bizType: 'BIZ_DETECT',
          bizId: this.formData.bizId || null,
          cut: true,
          startNodeId: startNodeId,
          endNodeId: endNodeId,
          portList: portList,
          processName: processName
        }
        if (this.formData.aPortData && this.formData.aPortData.regionName) {
          params.startRegionName = this.formData.aPortData.regionName // 操作日志需要，后端不需要此参数
        } else {
          params.startRegionName = ''
        }
        if (this.formData.zPortData && this.formData.zPortData.regionName) {
          params.endRegionName = this.formData.zPortData.regionName // 操作日志需要，后端不需要此参数
        } else {
          params.endRegionName = ''
        }
        params.functionName = this.parentVM.functionName || this.formData.functionName // 操作日志需要，后端不需要此参数
        params.actionName = this.formData.actionName // 操作日志需要，后端不需要此参数
        params.bizName = this.formData.bizName || this.$t('INTELLIGENT_CONNECT') // 操作日志需要，后端不需要此参数
        taskGroup.bizDetect(params).then(res => {
          if (res && res.processId) {
            this.showConfirm = false
            this.processId = res.processId
            this.$message.success(this.$t('REQUEST_SUCCESS'))
            this.$emit('taskChange', true)
            this.progress = 0
            this.completed = false
            this.failed = false
            this.taskIdList = res.taskIdList.map(i => {
              return {
                taskId: i,
                progress: 0
              }
            })
            this.getByProcessId()
          }
        })
      }
    }
  }
</script>

<style>
  .w-150 {
    width: 150px;
  }
</style>
